package views;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLDataException;
import java.sql.SQLException;
import java.sql.Time;
import java.util.Arrays;

import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;

import controllers.TimeSlot;
import controllers.Vehicle;
import controllers.VehicleType;

import db.TimeSlotDAO;
import db.VehicleDAO;
import db.VehicleTypeDAO;
import javax.swing.table.TableCellRenderer;

public class ViewVehicleTypesFrame extends JFrame {

	private static final int WIDTH=800;
	private static final int HEIGHT=500;
	private static final String TITLE = "View / Edit Vehicle Types";
	private static Object[][] vehicleTypes;
	private static java.util.List<VehicleType> list;
	private static JButton add, edit, delete, save, clear;
	private static JTable table;
	//private static Object columnNames[] = {"Vehicle Type", "Number of Seats"};
	private static JScrollPane scrollPane;
	private static MyTableModel model;
	private static Container c;
	private static int editRow;

	public ViewVehicleTypesFrame(int xBound, int yBound){
		this.setBounds(xBound+100, yBound+50, WIDTH, HEIGHT);
		this.setResizable(false);
		this.setTitle(TITLE);
		this.setVisible(true);

		c = this.getContentPane();
		c.setLayout(null);
		scrollPane = new JScrollPane();
		c.add(scrollPane);
		updateRows();

		add = new JButton("Add");
		add.setBounds(25, 425, 100, 30);
		add.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				new AddVehicleTypeFrame(getX(),getY());
			}
		});
		c.add(add);

		edit = new JButton("Edit");
		edit.setBounds(135, 425, 100, 30);
		edit.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				int row = table.getSelectedRow();
				editRow = row;
				if(row!=-1){
					model.editRow(row);
					editRow = row;
					table.editCellAt(row, table.getSelectedColumn());
					table.getCellEditor().addCellEditorListener(new CellEditorListener(){
						@Override
						public void editingCanceled(ChangeEvent e) {
						}
						@Override
						public void editingStopped(ChangeEvent e) {
							save.setEnabled(true);
							edit.setEnabled(false);
						}
					});
				}
				else{
					System.out.println("Nothing Selected");
				}
			}
		});
		c.add(edit);

		delete = new JButton("Delete");
		delete.setBounds(245, 425, 100, 30);
		delete.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				if(JOptionPane.showConfirmDialog(getComponent(0), "Are you sure you want to delete? This cannot be undone.", "Delete", 0)==0){
					int row = table.getSelectedRow();
					if(row!=-1){
						if(VehicleTypeDAO.deleteVehicleType(list.get(row))){
							model.removeRow(row);
							updateRows();
						}
						else{
							JOptionPane.showMessageDialog(getComponent(0), "Deletion Failed! Vehicles associated with this vehicle type must be deleted first!", "Deletion Failed!", 0);
						}
					}
					else{
						System.out.println("Nothing selected");
					}
				}
			}
		});
		c.add(delete);

		save = new JButton("Save");
		save.setBounds(355, 425, 100, 30);
		save.setEnabled(false);
		save.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try{
				VehicleType temp = list.get(editRow);
				temp.setName(table.getValueAt(editRow, 0).toString());
				temp.setNumOfSeats(Integer.parseInt(table.getValueAt(editRow, 1).toString()));
                                temp.setIgnoreGenerate(Boolean.parseBoolean(table.getValueAt(editRow, 2).toString()));
				VehicleTypeDAO.saveVehicleType(temp);
				save.setEnabled(false);
				model.editRow(-2);
				edit.setEnabled(true);
				}
				catch(Exception e){
					e.printStackTrace();
					JOptionPane.showMessageDialog(getComponent(0), "Save Failed! Please make sure your changes are valid.","Save Failed!",0);
					updateRows();
					edit.setEnabled(true);
				}
			}
		});
		c.add(save);
		
		clear = new JButton("Clear");
		clear.setBounds(465, 425, 100, 30);
		clear.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				updateRows();
				edit.setEnabled(true);
				save.setEnabled(false);
			}
		});
		c.add(clear);

	}

	public static void updateRows(){
		list = VehicleTypeDAO.getVehicleTypes();
		vehicleTypes = new Object[list.size()][3];
		for(int i=0;i<list.size();i++){
			vehicleTypes[i][0] = list.get(i).getName();
			vehicleTypes[i][1] = ""+list.get(i).getNumOfSeats();
                        vehicleTypes[i][2] = list.get(i).isIgnoreGenerate();
		}

		Object columnNames[] = {"Vehicle Type", "Number of Seats", "Ignore Generate"};
		model = new MyTableModel(vehicleTypes, columnNames);
		table = new JTable(model);
		table.setRowHeight(30);
		table.getTableHeader().setReorderingAllowed(false);
		table.addRowSelectionInterval(0, 0);
		TableColumn col = table.getColumnModel().getColumn(1);
		col.setCellEditor(new customNumOfSeatsEditor());
                TableColumn col2 = table.getColumnModel().getColumn(2);
                col2.setCellEditor(new customIgnoreGenerateEditor(new JCheckBox()));
                col2.setCellRenderer(new customIgnoreGenerateRenderer());
		c.remove(scrollPane);
		scrollPane = new JScrollPane(table);
		scrollPane.setBounds(25,0,750,400);
		c.add(scrollPane);
	}

}

class customNumOfSeatsEditor extends AbstractCellEditor implements TableCellEditor{
	
	final JSpinner spinner;
	
	public customNumOfSeatsEditor(){
		spinner = new JSpinner();
		String[] numOfSeats = new String[50];
		for(int i =0; i<numOfSeats.length;i++){
			numOfSeats[i] = ""+(i+1);
		}
		spinner.setModel(new SpinnerListModel(Arrays.asList(numOfSeats)));
	}
	
	@Override
	public Object getCellEditorValue() {
		// TODO Auto-generated method stub
		return spinner.getValue();
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object arg1,
			boolean isSelected, int arg3, int arg4) {
		try{
		spinner.setValue(arg1);
		}
		catch(Exception e){}
		return spinner;
	}
}

class customIgnoreGenerateEditor extends DefaultCellEditor{
	public customIgnoreGenerateEditor(JCheckBox arg0) {
		super(arg0);
	}
}

class customIgnoreGenerateRenderer extends JCheckBox implements TableCellRenderer{

	@Override
	public Component getTableCellRendererComponent(JTable table, Object value,
			boolean isSelected, boolean arg3, int arg4, int arg5) {
        if (isSelected) {
            setForeground(table.getSelectionForeground());
            super.setBackground(table.getSelectionBackground());
        } else {
            setForeground(table.getForeground());
            setBackground(table.getBackground());
        }
		setSelected(Boolean.parseBoolean(value.toString()));
		return this;
	}
}
